package com.macro.mall.tiny.modules.oms.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.modules.oms.dto.UserInfoParam;
import com.macro.mall.tiny.modules.oms.dto.UserListQueryParam;
import com.macro.mall.tiny.modules.oms.dto.UserLoginParam;
import com.macro.mall.tiny.modules.oms.dto.UserParam;
import com.macro.mall.tiny.modules.oms.dto.UserUpdateParam;
import com.macro.mall.tiny.modules.oms.model.User;
import com.macro.mall.tiny.modules.oms.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.macro.mall.tiny.security.util.JwtTokenUtil;

import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 顾客表 前端控制器
 * </p>
 *
 * @author macro
 * @since 2023-11-07
 */
@Controller
@Tag(name = "UserController", description = "顾客管理")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Operation(summary = "顾客登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@Validated @RequestBody UserLoginParam loginParam) {
        String token = userService.login(loginParam);
        if (token == null) {
            return CommonResult.validateFailed("手机号或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @Operation(summary = "顾客退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if (token != null && token.startsWith(tokenHead)) {
            token = token.substring(tokenHead.length());
            userService.logout(token);
        }
        return CommonResult.success(null, "退出成功");
    }

    @Operation(summary = "顾客列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<User>> listUsers(UserListQueryParam queryParam) {
        try {
            Page<User> userList = userService.pageList(queryParam);
            return CommonResult.success(CommonPage.restPage(userList));
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage() + e.toString());
        }
    }

    @Operation(summary = "获取顾客信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<User> getUserInfo(UserInfoParam userInfoParam) {
        try {
            User user;

            // 从token中解析用户ID，如果queryParam中没有提供userId

            if (userInfoParam.getUserId() == null && userInfoParam.getToken() != null) {
                try {
                    String userIdStr = jwtTokenUtil.getUserNameFromToken(userInfoParam.getToken());
                    if (userIdStr != null && !userIdStr.isEmpty()) {
                        userInfoParam.setUserId(Integer.parseInt(userIdStr));
                    }
                } catch (Exception e) {
                    return CommonResult.failed("无效的token");
                }
            }

            user = null;
            // 如果传入了userId，直接使用userId查询
            if (userInfoParam.getUserId() != null) {
                user = userService.getUserInfo(userInfoParam.getUserId());
            }

            if (user == null) {
                return CommonResult.failed("用户不存在");
            }

            return CommonResult.success(user);
        } catch (Exception e) {
            return CommonResult.failed("获取用户信息失败: " + e.getMessage());
        }
    }
    

    @Operation(summary = "添加顾客")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createUser(@Validated @RequestBody UserParam userParam) {
        boolean success = userService.create(userParam);
        if (success) {
            return CommonResult.success(null, "添加成功");
        } else {
            return CommonResult.failed("添加失败");
        }
    }
    
    @Operation(summary = "更新顾客信息")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateUserInfo(@Validated @RequestBody UserUpdateParam updateParam) {
        try {
            // 如果userId为null或0，从token中解析用户ID
            if (updateParam.getUserId() == null || updateParam.getUserId() == 0) {
                if (updateParam.getToken() != null) {
                    String userIdStr = jwtTokenUtil.getUserNameFromToken(updateParam.getToken());
                    if (userIdStr != null && !userIdStr.isEmpty()) {
                        updateParam.setUserId(Integer.parseInt(userIdStr));
                    } else {
                        return CommonResult.failed("无效的token");
                    }
                }
            }
            
            // 确保userId已提供且有效
            if (updateParam.getUserId() == null || updateParam.getUserId() <= 0) {
                return CommonResult.failed("用户ID不能为空");
            }
            
            boolean success = userService.updateUserInfo(updateParam.getUserId(), updateParam);
            if (success) {
                return CommonResult.success(null, "更新成功");
            } else {
                return CommonResult.failed("更新失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("更新用户信息失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "删除顾客")
    @RequestMapping(value = "/delete/{userId}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@PathVariable Integer userId) {
        boolean success = userService.delete(userId);
        if (success) {
            return CommonResult.success(null, "删除成功");
        } else {
            return CommonResult.failed("删除失败");
        }
    }
}
